package cn.oms.manage.service.impl;

import cn.oms.commons.ex.ServiceException;
import cn.oms.commons.pojo.vo.PageData;
import cn.oms.commons.web.ServiceCode;
import cn.oms.manage.dao.persist.repository.ICustomerRepository;
import cn.oms.manage.dao.persist.repository.IDepartmentRepository;
import cn.oms.manage.dao.persist.repository.IOrderRepositry;
import cn.oms.manage.dao.persist.repository.IRecordRepository;
import cn.oms.manage.pojo.entity.Customer;
import cn.oms.manage.pojo.param.CustomerAddNewParam;
import cn.oms.manage.pojo.param.CustomerUpdateInfoParam;
import cn.oms.manage.pojo.vo.CustomerListItemVO;
import cn.oms.manage.pojo.vo.CustomerStandardVO;
import cn.oms.manage.pojo.vo.DepartmentStandardVO;
import cn.oms.manage.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Value("${oms.crud.default-query-page-size}")
    private Integer defaultQueryPageSize;

    @Autowired
    private ICustomerRepository customerRepository;

    @Autowired
    private IDepartmentRepository departmentRepository;
    
    @Autowired
    IOrderRepositry orderRepositry;
    
    @Autowired
    IRecordRepository recordRepository;

    public CustomerServiceImpl() {
        log.debug("创建业务类对象：CustomerServiceImpl");
    }

    @Override
    public void addNew(CustomerAddNewParam customerAddNewParam) {
        log.debug("开始处理【添加用户】的业务，参数：{}", customerAddNewParam);

        // department表是否存在
        DepartmentStandardVO department = departmentRepository.getStandardById(customerAddNewParam.getDepartmentId());
        if (department == null) {
            String message = "添加用户失败！科室不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        Customer customer = new Customer();
        BeanUtils.copyProperties(customerAddNewParam, customer);


        log.debug("即将执行插入数据，参数：{}", customer);
        int rows = customerRepository.insert(customer);
        if (rows != 1) {
            String message = "添加用户失败！服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除用户】的业务，参数：{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        CustomerStandardVO customer = customerRepository.getStandardById(id);
        log.debug("根据ID={}检查用户数据是否存在，查询结果：{}", id, customer);
        // 判断查询结果是否为null
        if (customer == null) {
            String message = "删除用户失败，尝试删除的用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        //TODO 是否有主键在one_order，treat_recor表中

        int Count = orderRepositry.countByCustomer(id);
        if (Count > 0) {
            String message = "删除客户失败，仍有订单与该客户关联！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        Count = recordRepository.countByCustomer(id);
        if (Count > 0) {
            String message = "删除客户失败，仍有诊断记录与该客户关联！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        
        // 调用Mapper对象的deleteById()方法执行删除
        log.debug("即将执行删除，参数：{}", id);
        customerRepository.deleteById(id);
    }

    @Override
    public void updateInfoById(Long id, CustomerUpdateInfoParam customerUpdateInfoParam) {
        log.debug("开始处理【修改用户详情】的业务，ID：{}，新数据：{}", id, customerUpdateInfoParam);
        // 调用Mapper对象的getStandardById()执行查询
        CustomerStandardVO queryResult = customerRepository.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：抛出异常
            String message = "修改用户详情失败，尝试修改的用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
//        customerUpdateInfoParam.setDepartmentName(departmentRepository.getStandardById(customerUpdateInfoParam.getDepartmentId()).getName());

        // 创建Customer对象
        Customer customer = new Customer();
        // 复制属性，设置ID
        BeanUtils.copyProperties(customerUpdateInfoParam, customer);
        customer.setId(id);
        // 调用Mapper对象的update()方法执行修改
        customerRepository.update(customer);
    }

    @Override
    public CustomerStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询用户详情】的业务，参数：{}", id);
        CustomerStandardVO queryResult = customerRepository.getStandardById(id);
        // CustomerStandardVO queryResult = customerRedisRepository.get(id);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "查询用户详情失败，用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<CustomerListItemVO> list(Integer pageNum) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}", pageNum);
        PageData<CustomerListItemVO> pageData = customerRepository.list(pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<CustomerListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageData<CustomerListItemVO> pageData = customerRepository.list(pageNum, pageSize);
        return pageData;
    }
}
